#' qc_heatcor UI Function
#'
#' @description A shiny Module.
#'
#' @param id,input,output,session Internal parameters for {shiny}.
#'
#' @noRd
#'
#' @importFrom shiny NS tagList
mod_qc_heatcor_ui <- function(id){
  ns <- NS(id)
  tagList(
    fluidRow(
      column(4,sliderInput(ns("height"),"Height", min = 100, max = 1000, value = 300)),
      column(2),
      column(4, sliderInput(ns("width"), "Width", min = 100, max = 1000, value = 400)),
      column(2),
      column(6, colourpicker::colourInput(ns("col1"), "Select colour of group1", "#66c2a5")),
      column(6, colourpicker::colourInput(ns("col2"), "Select colour of group2", "#fc8d62")),
      column(6,
             shinyWidgets::pickerInput(
               inputId = ns("colmap"),
               label = "Color Style of Heatmap",
               selected = "RdYlBu",
               choices = list(
                 Diverging = c(
                   "BrBG", "PiYG", "PRGn", "PuOr", "RdBu", "RdGy", "RdYlBu", "RdYlGn", "Spectral"
                 )
               ),
               options = list(
                 `live-search` = TRUE)
             )
      )
    ),
    downloadLink(ns('dlcorPlot'), 'Download plot as PDF'),
    shinycustomloader::withLoader(
      plotOutput(ns("heatcor"))
    )

  )
}

#' qc_heatcor Server Functions
#' @importFrom stats mad
mod_qc_heatcor_server <- function(id,updata=""){
  moduleServer( id, function(input, output, session){
    ns <- session$ns
    #load(file = 'tests/step1-output.Rdata')

    exprSet <- reactive({
      updata$genes_expr()
    })

    group_list <- reactive({
      updata$group_list()
    })


    colD <- reactive({
      group_list <- group_list()
      col_fun = c(input$col1,input$col2)
      names(col_fun) <- unique(group_list)
      ComplexHeatmap::HeatmapAnnotation(group = group_list, col = list(group = col_fun))
    })

    M <- reactive({
      exprSet <- exprSet()
      exprSet=exprSet[names(sort(apply(exprSet, 1,mad),decreasing = T)[1:500]),]
      stats::cor(exprSet)
    })

    plotcor <- function() {
      M <- M()
      colD <- colD()
      # pheatmap::pheatmap(M,
      #                    show_rownames = F,
      #                    annotation_col = colD)
      ComplexHeatmap::Heatmap(
        M,
        show_row_names = FALSE,
        show_column_names = TRUE,
        col = colorRampPalette(rev(RColorBrewer::brewer.pal(n = 7, name = input$colmap)))(100),
        top_annotation = colD,
        heatmap_legend_param = list(
          title = ""
        )
      )
    }

    output$heatcor <- renderPlot(width = function() input$width,
                                 height = function() input$height,
                                 res = 100,
                                 {
                                   plotcor()
                                 })

    # Create the button to download the plot as PDF
    output$dlcorPlot <- downloadHandler(
      filename = function() {
        paste('heatcorPlot_', Sys.Date(), '.pdf', sep='')
      },
      content = function(file) {
        ggplot2::ggsave(file, plotcor(), width = input$width/100, height = input$height/100, dpi = 300, units = "in", limitsize = FALSE)
      }
    )
  })
}

## To be copied in the UI
# mod_qc_heatcor_ui("qc_heatcor_ui_1")

## To be copied in the server
# mod_qc_heatcor_server("qc_heatcor_ui_1")
